package com.bangbang.mq;


import com.bangbang.pojo.TbAdvertisingOrder;
import com.bangbang.service.ITbAdvertisingOrderService;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.util.Objects;


@Component
@RocketMQTransactionListener(txProducerGroup = "orderGroup")
public class MessageInTransactionListner implements RocketMQLocalTransactionListener {


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ITbAdvertisingOrderService orderServiceI;

    @Override//执行本地事务方法
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        String id =  message.getHeaders().getId().toString();
        try {
            TbAdvertisingOrder order = (TbAdvertisingOrder) o;
            String messageBody = new String((byte[]) message.getPayload());
            System.err.println("orderNum"+order.getOrderId());//订单号
            System.err.println("serialNum"+order.getOrderRunning());//流水号
            System.err.println("消息内容"+messageBody);
            //修改订单状态
            //TODO
            orderServiceI.updateById(order);
            redisTemplate.opsForHash().put("transaction-message",id,"1");
            return RocketMQLocalTransactionState.COMMIT;
        }catch (Exception e){
            //失败后将修改状态为 2
            redisTemplate.opsForHash().put("transaction-message",id,"2");
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
    //本地事务回查
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        //从redis中取出数据 判断订单状态
        String status = (String) redisTemplate.opsForHash().get("transaction-message", message.getHeaders().getId().toString());
        if(Objects.equals(status,"1")){
            return RocketMQLocalTransactionState.COMMIT;
        }else if(Objects.equals(status,"2")){
            return RocketMQLocalTransactionState.ROLLBACK;
        }
            return RocketMQLocalTransactionState.UNKNOWN;
    }
}
